<template>
  <div class="mdb-import-container" style="padding: 20px;">
    <h2>MDB 文件导入与解析</h2>

    <!-- 文件上传与解析 -->
    <el-card class="upload-card" shadow="never" style="margin-bottom: 20px;">
      <el-upload
        ref="upload"
        :auto-upload="false"
        :on-change="handleFileChange"
        :limit="1"
        :file-list="fileList"
        accept=".mdb"
      >
        <el-button size="small" type="primary">选择 MDB 文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传 .mdb 文件</div>
      </el-upload>

      <el-button
        type="success"
        size="small"
        style="margin-left: 10px;"
        @click="handleParse"
        :disabled="!selectedFile"
      >
        解析文件
      </el-button>
    </el-card>

    <!-- 上半部分：数据库表信息 -->
    <el-card v-if="tables.length > 0" class="tables-card" shadow="never" style="margin-bottom: 20px;">
      <h3>数据库表信息</h3>
      <el-table
        :data="tables"
        border
        highlight-current-row
        @current-change="handleTableSelect"
        style="width: 100%;"
      >
        <el-table-column prop="tableName" label="数据库表名" width="200"></el-table-column>
        <el-table-column label="显示图层名">
          <template slot-scope="scope">
            <el-input v-model="scope.row.displayLayerName" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="图层类型">
          <template slot-scope="scope">
            <el-select v-model="scope.row.layerType" placeholder="请选择" size="small" @change="onLayerTypeChange(scope.row)">
              <el-option
                v-for="item in layerTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
              <el-option value="custom" label="自定义...">
                <span @click.stop="openCustomLayerType(scope.row)" style="color: #409EFF; cursor: pointer;">+ 自定义...</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="注记对应的属性">
          <template slot-scope="scope">
            <el-select v-model="scope.row.labelField" placeholder="请选择字段" size="small" clearable>
              <el-option
                v-for="field in getFieldOptions(scope.row)"
                :key="field.fieldName"
                :label="field.fieldName"
                :value="field.fieldName"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 下半部分：字段信息 -->
    <el-card v-if="selectedTable" class="fields-card" shadow="never">
      <h3>字段信息（表：{{ selectedTable.tableName }}）</h3>
      <el-table :data="selectedTable.fields" border style="width: 100%;">
        <el-table-column prop="fieldName" label="字段名" width="180"></el-table-column>
        <el-table-column label="显示名">
          <template slot-scope="scope">
            <el-input v-model="scope.row.displayName" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="是否是注记">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isLabel" active-text="是" inactive-text="否"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否弹窗显示">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isPopup" active-text="是" inactive-text="否"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否列表显示">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isList" active-text="是" inactive-text="否"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否查询字段">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isQuery" active-text="是" inactive-text="否"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否编辑字段">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isEdit" active-text="是" inactive-text="否"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否图片字段">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isImage" active-text="是" inactive-text="否"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="editField(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteField(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 自定义图层类型对话框 -->
    <el-dialog title="自定义图层类型" :visible.sync="customLayerDialogVisible" width="30%">
      <el-input v-model="customLayerTypeValue" placeholder="请输入自定义图层类型"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="customLayerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCustomLayerType">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MDBImportPage',
  data() {
    return {
      fileList: [],
      selectedFile: null,

      // 表格数据：所有表
      tables: [],
      selectedTable: null,

      // 图层类型选项
      layerTypeOptions: [
        { label: '点图层', value: 'point' },
        { label: '线图层', value: 'line' },
        { label: '面图层', value: 'polygon' },
        { label: '注记图层', value: 'annotation' },
        { label: '栅格图层', value: 'raster' }
      ],
      customLayerDialogVisible: false,
      customLayerTypeValue: '',
      currentCustomRow: null // 当前正在编辑自定义类型的行
    };
  },
  methods: {
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1); // 只保留最后一个
      this.selectedFile = file.raw;
    },

    handleParse() {
      if (!this.selectedFile) return;

      // 模拟上传并解析（实际应调用 $http 请求）
      this.$message.info('正在上传并解析文件...');

      // 模拟异步解析返回结果（实际应替换为 axios 请求）
      setTimeout(() => {
        // 模拟服务端返回的解析结果
        const mockResult = this.mockParseResult();

        this.tables = mockResult.tables;
        // 默认选中第一个表
        if (this.tables.length > 0) {
          this.selectedTable = this.tables[0];
        }

        this.$message.success('文件解析成功！');
      }, 1500);
    },

    // 模拟服务端返回的数据结构
    mockParseResult() {
      return {
        tables: [
          {
            tableName: 'roads',
            comment: '道路表',
            displayLayerName: '道路',
            layerType: 'line',
            labelField: '',
            fields: [
              { fieldName: 'id', comment: 'ID', displayName: '编号', isLabel: false, isPopup: true, isList: true, isQuery: true, isEdit: false, isImage: false },
              { fieldName: 'name', comment: '名称', displayName: '道路名称', isLabel: true, isPopup: true, isList: true, isQuery: true, isEdit: true, isImage: false },
              { fieldName: 'type', comment: '类型', displayName: '道路类型', isLabel: false, isPopup: true, isList: true, isQuery: true, isEdit: true, isImage: false },
              { fieldName: 'image_url', comment: '图片路径', displayName: '图片', isLabel: false, isPopup: true, isList: false, isQuery: false, isEdit: true, isImage: true }
            ]
          },
          {
            tableName: 'buildings',
            comment: '建筑物表',
            displayLayerName: '建筑物',
            layerType: 'polygon',
            labelField: 'name',
            fields: [
              { fieldName: 'id', comment: 'ID', displayName: '编号', isLabel: false, isPopup: true, isList: true, isQuery: true, isEdit: false, isImage: false },
              { fieldName: 'name', comment: '名称', displayName: '建筑名称', isLabel: true, isPopup: true, isList: true, isQuery: true, isEdit: true, isImage: false },
              { fieldName: 'floors', comment: '楼层数', displayName: '楼层数', isLabel: false, isPopup: true, isList: true, isQuery: false, isEdit: true, isImage: false }
            ]
          }
        ]
      };
    },

    handleTableSelect(currentRow) {
      this.selectedTable = currentRow;
    },

    getFieldOptions(table) {
      return table.fields || [];
    },

    openCustomLayerType(row) {
      this.currentCustomRow = row;
      this.customLayerTypeValue = '';
      this.customLayerDialogVisible = true;
    },

    confirmCustomLayerType() {
      if (!this.customLayerTypeValue.trim()) {
        this.$message.error('请输入自定义图层类型');
        return;
      }

      const customValue = this.customLayerTypeValue.trim();
      // 添加到选项列表（可选）
      if (!this.layerTypeOptions.some(opt => opt.value === customValue)) {
        this.layerTypeOptions.push({ label: customValue, value: customValue });
      }

      // 设置当前行的图层类型
      if (this.currentCustomRow) {
        this.currentCustomRow.layerType = customValue;
      }

      this.customLayerDialogVisible = false;
      this.customLayerTypeValue = '';
      this.currentCustomRow = null;
    },

    editField(field) {
      this.$prompt('编辑字段名', '提示', {
        inputValue: field.displayName,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (value) field.displayName = value;
      }).catch(() => {});
    },

    deleteField(index) {
      this.$confirm('确定删除该字段？', '警告', {
        type: 'warning'
      }).then(() => {
        this.selectedTable.fields.splice(index, 1);
        this.$message.success('删除成功');
      }).catch(() => {});
    },

    onLayerTypeChange(row) {
      // 可以在这里添加逻辑，比如根据图层类型联动字段
    }
  }
};
</script>

<style scoped>
.mdb-import-container {
  font-family: Arial, sans-serif;
}
.upload-card, .tables-card, .fields-card {
  border-radius: 6px;
}
</style>
